Python syntax and semantics
part 32/45 · 74.8 KB total
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Exceptions
Python supports (and extensively uses) exception handling as a means of testing for error conditions and other "exceptional" events in a program.
Python style calls for the use of exceptions whenever an error condition might arise. Rather than testing for access to a file or resource before actually using it, it is conventional in Python to just go ahead and try to use it, catching the exception if access is rejected.
Exceptions can also be used as a more general means of non-local transfer of control, even when an error is not at issue. For instance, the Mailman mailing list software, written in Python, uses exceptions to jump out of deeply nested message-handling logic when a decision has been made to reject a message or hold it for moderator approval.
Exceptions are often used as an alternative to the if-block, especially in threaded situations. A commonly invoked motto is EAFP, or "It is Easier to Ask for Forgiveness than Permission,"cite-ref-30[26] which is attributed to Grace Hopper.cite-ref-31[27]cite-ref-nutshell-32-0[28] The alternative, known as LBYL, or "Look Before You Leap", explicitly tests for pre-conditions.cite-ref-33[29]
In this first code sample, following the LBYL approach, there is an explicit check for the attribute before access:
if hasattr(spam, 'eggs'):
ham = spam.eggs
else:
handle_missing_attr()
This second sample follows the EAFP paradigm:
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────